package org.hk.proxy.client.handlers;

import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.timeout.IdleStateEvent;
import io.netty.handler.timeout.IdleStateHandler;
import org.hk.proxy.client.ClientChannelManagement;
import org.hk.proxy.protocol.ProxyMessage;

public class PingHandler extends IdleStateHandler {
    public PingHandler(int readerIdleTimeSeconds, int writerIdleTimeSeconds, int allIdleTimeSeconds) {
        super(readerIdleTimeSeconds, writerIdleTimeSeconds, allIdleTimeSeconds);
    }

    @Override
    protected void channelIdle(ChannelHandlerContext ctx, IdleStateEvent evt) throws Exception {
        if(IdleStateEvent.FIRST_READER_IDLE_STATE_EVENT == evt && ctx.channel()== ClientChannelManagement.cmdChannel){
            ctx.channel().close();
        }else if(IdleStateEvent.FIRST_WRITER_IDLE_STATE_EVENT == evt && ctx.channel()== ClientChannelManagement.cmdChannel){
            ProxyMessage proxyMessage = new ProxyMessage();
            proxyMessage.setType(ProxyMessage.HEART_PACKAGE);
            ctx.channel().writeAndFlush(proxyMessage);
        }
    }
}
